/*
 * Powered By dico
 * Since 2017 - 2018
 */
package com.seeyoui.kensite.bussiness.exam.exercise.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.seeyoui.kensite.bussiness.exam.examResult.service.MarkingService;
import com.seeyoui.kensite.bussiness.exam.exercise.domain.Exercise;
import com.seeyoui.kensite.bussiness.exam.exercise.service.ExerciseService;
import com.seeyoui.kensite.common.base.controller.BaseController;
import com.seeyoui.kensite.common.base.domain.EasyUIDataGrid;
import com.seeyoui.kensite.common.base.domain.Page;
import com.seeyoui.kensite.common.constants.StringConstant;
import com.seeyoui.kensite.common.util.DateUtils;
import com.seeyoui.kensite.common.util.RequestResponseUtil;
import com.seeyoui.kensite.common.util.Result;
import com.seeyoui.kensite.common.util.excel.ExportExcel;
import com.seeyoui.kensite.framework.system.util.UserUtils;
/**
 * Exercise
 * @author dico
 * @version 2.0
 * @since 1.0
 * @date 2018-01-08
 */

@Controller
@RequestMapping(value = "exam/exercise")
public class ExerciseController extends BaseController {
	
	@Autowired
	private ExerciseService exerciseService;
	@Autowired
	private MarkingService markingService;
	
	/**
	 * 展示列表页面
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:view")
	@RequestMapping(value = "/{page}")
	public ModelAndView view(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page) throws Exception {
		return new ModelAndView("bussiness/exam/exercise/"+page, modelMap);
	}
	
	/**
	 * 根据ID查询单条数据
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:select")
	@RequestMapping(value = "/data/{id}")
	@ResponseBody
	public Object data(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String id) throws Exception {
		Exercise exercise = exerciseService.findOne(id);
		return exercise;
	}
	
	/**
	 * 根据ID查询单条数据并返回相应表单
	 * @param modelMap
	 * @param module
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:view")
	@RequestMapping(value = "/form/{page}/{id}")
	public ModelAndView form(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, @PathVariable String page, @PathVariable String id) throws Exception {
		Exercise exercise = exerciseService.findOne(id);
		modelMap.put("exercise", exercise);
		return new ModelAndView("bussiness/exam/exercise/"+page, modelMap);
	}
	
	/**
	 * 获取列表展示数据
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:select")
	@RequestMapping(value = "/list/data", method=RequestMethod.POST)
	@ResponseBody
	public Object listData(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		List<Exercise> exerciseList = exerciseService.findList(exercise);
		int total = exerciseService.findTotal(exercise);
		EasyUIDataGrid eudg = new EasyUIDataGrid();
		eudg.setTotal(String.valueOf(total));
		eudg.setRows(exerciseList);
		return eudg;
	}
	
	/**
	 * 获取列表展示数据带分页器用于jsp自己做分页
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:view")
	@RequestMapping(value = "/list/page", method=RequestMethod.POST)
	@ResponseBody
	public Object listPage(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		List<Exercise> exerciseList = exerciseService.findList(exercise);
		int total = exerciseService.findTotal(exercise);
		Page<Exercise> page = new Page<Exercise>(exercise.getPage(), exercise.getRows(), total);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("rows", exerciseList);
		dataMap.put("page", page);
		return dataMap;
	}
	
	/**
	 * 获取所有数据
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:select")
	@RequestMapping(value = "/list/all", method=RequestMethod.POST)
	@ResponseBody
	public Object listAll(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		List<Exercise> exerciseList = exerciseService.findAll(exercise);
		return exerciseList;
	}
	
	/**
	 * 保存新增的数据
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:insert")
	@RequestMapping(value = "/save", method=RequestMethod.POST)
	@ResponseBody
	public String save(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		if (!beanValidator(modelMap, exercise)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		exerciseService.save(exercise);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 保存修改的数据
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:update")
	@RequestMapping(value = "/update", method=RequestMethod.POST)
	@ResponseBody
	public String update(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		if (!beanValidator(modelMap, exercise)){
			RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.FALSE);
			return null;
		}
		exerciseService.update(exercise);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 删除数据库
	 * @param modelMap
	 * @param exerciseId
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:delete")
	@RequestMapping(value = "/delete", method=RequestMethod.POST)
	@ResponseBody
	public String delete(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, String id) throws Exception {
		List<String> listId = Arrays.asList(id.split(","));
		exerciseService.delete(listId);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}
	
	/**
	 * 假删除
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:delete")
	@RequestMapping(value = "/remove", method=RequestMethod.POST)
	@ResponseBody
	public String remove(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		exerciseService.remove(exercise);
		RequestResponseUtil.putResponseStr(session, response, request, modelMap, StringConstant.TRUE);
		return null;
	}

	/**
	 * 导出Excel数据
	 * @param modelMap
	 * @param exercise
	 * @return
	 * @throws Exception
	 */
	//@RequiresPermissions("exam:exercise:export")
	@RequestMapping(value = "/export")
	public String export(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap, Exercise exercise) throws Exception {
		String fileName = DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<Exercise> exerciseList = exerciseService.findAll(exercise);
		new ExportExcel(null, Exercise.class).setDataList(exerciseList).write(response, fileName).dispose();
		return null;
	}

	@RequestMapping(value = "/submit", method=RequestMethod.POST)
	@ResponseBody
	public Result submit(HttpServletRequest request, String data) throws Exception {
		String json = data.replaceAll("&quot;", "\"");
		String exerciseId = (String)JSONPath.read(json, "$.exerciseId");
		JSONObject answer = (JSONObject)JSONPath.read(json, "$.answer");
		Exercise exercise = exerciseService.findOne(exerciseId);
		if(null == exercise) {
			logger.error("该练习不存在：exerciseId=" + exerciseId + "  userId=" + UserUtils.getUser(request).getId());
			return Result.failure("该练习不存在：exerciseId=%s userId=%s", exerciseId, UserUtils.getUser(request).getId());
		}
		exercise.setSubmitTime(new Date());
		exercise.setResult(answer.toJSONString());
		exerciseService.update(exercise);

		// 异步线程评分
		markingService.markingExercise(exercise);

		return Result.success(null, "练习提交成功！");
	}
	
	/**
	 * 查询登录用户的历史考试成绩列表，仅获取前10条记录，按考试时间倒序排序<br>
	 * paperId字段为得分,remarks字段为排名<br>
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/topMyExercise", method=RequestMethod.POST)
	@ResponseBody
	public Object topMyExercise(HttpSession session,
			HttpServletResponse response, HttpServletRequest request,
			ModelMap modelMap) throws Exception {
		// 当前登录用户ID
		String userId = UserUtils.getUser(request).getId();
		List<Exercise> exerciseList = exerciseService.topMyExercise(userId);
		if(exerciseList.size() > 10) {
			return Result.success(exerciseList.subList(0, 9));
		}
		return Result.success(exerciseList);
	}
}